<template>
	<view class="content">
		<!-- #ifdef MP-WEIXIN -->
		<button type="default" open-type="getUserInfo" @getuserinfo="loginByWeixin">微信登录</button>
		<button type="default" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">获取微信绑定手机号</button>
		<button type="default" @tap="code2SessionWeixin">获取微信openid</button>
		<button type="default" @tap="bindWeixin">绑定微信</button>
		<button type="default" @tap="unbindWeixin">解绑微信</button>
		<!-- #endif -->
		<!-- #ifdef APP-PLUS -->
		<template v-if="hasWeixinAuth">
			<button type="default" @tap="loginByWeixin">微信登录</button>
			<button type="default" @tap="bindWeixin">绑定微信</button>
			<button type="default" @tap="unbindWeixin">解绑微信</button>
		</template>
		<template v-else>
			<view class="tips">未包含微信登录模块</view>
		</template>
		<!-- #endif -->
	</view>
</template>

<script>
	const db = uniCloud.database();
	const app = getApp();
	let weixinAuthService
	export default {
		data() {
			return {
				hasWeixinAuth: false,
				wxUserInfo: null
			}
		},
		onLoad() {
			// #ifdef APP-PLUS
			plus.oauth.getServices((services) => {
				weixinAuthService = services.find((service) => {
					return service.id === 'weixin'
				})
				if (weixinAuthService) {
					this.hasWeixinAuth = true
				}
			});
			// #endif	
		},
		methods: {
			getWeixinCode() {
				return new Promise((resolve, reject) => {
					// #ifdef APP-PLUS
					weixinAuthService.authorize(function(res) {
						resolve(res.code)
					}, function(err) {
						console.log(err)
						reject(new Error('微信登录失败'))
					});
					// #endif
					// #ifdef MP-WEIXIN
					uni.login({
						provider: 'weixin',
						success(res) {
							resolve(res.code)
						},
						fail(err) {
							reject(new Error('微信登录失败'))
						}
					})
					// #endif
				})
			},
			code2SessionWeixin() {
				this.getWeixinCode().then((code) => {
					return uniCloud.callFunction({
						name: 'user-center',
						data: {
							action: 'code2SessionWeixin',
							params: {
								code,
							}
						}
					})
				}).then((res) => {
					uni.showModal({
						showCancel: false,
						content: JSON.stringify(res.result)
					})
				}).catch((e) => {
					console.error(e)
					uni.showModal({
						showCancel: false,
						content: '微信登录失败，请稍后再试'
					})
				})
			},
			unbindWeixin() {
				uniCloud.callFunction({
					name: 'user-center',
					data: {
						action: 'unbindWeixin'
					},
					success(res) {
						uni.showModal({
							showCancel: false,
							content: JSON.stringify(res.result)
						})
					},
					fail(e) {
						console.error(e)
						uni.showModal({
							showCancel: false,
							content: '微信解绑失败，请稍后再试'
						})
					}
				})
			},
			bindWeixin() {
				this.getWeixinCode().then((code) => {
					return uniCloud.callFunction({
						name: 'user-center',
						data: {
							action: 'bindWeixin',
							params: {
								code: code,
							}
						}
					})
				}).then((res) => {
					uni.showModal({
						showCancel: false,
						content: JSON.stringify(res.result)
					})
				}).catch(() => {
					uni.showModal({
						showCancel: false,
						content: '微信绑定失败，请稍后再试'
					})
				})
			},
			async loginByWeixin(e) {
				await this.getUserInfo();
				this.getWeixinCode().then((code) => {
					return uniCloud.callFunction({
						name: 'user-center',
						data: {
							action: 'loginByWeixin',
							params: {
								code,
							}
						}
					})
				}).then((res) => {
					console.log(res)
					uni.showToast({
						title: "登陆成功",
						complete: () => {
							app.globalData.userInfo = res.result.userInfo;
							app.globalData.hasLogin = true;
							uni.setStorageSync('sessionKey', res.result.sessionKey)
						}
					})
					if (res.result.code === 0) {
						db.collection('uni-id-users').doc(res.result.uid).update({
							nickname: this.wxUserInfo.nickName,
							gender: this.wxUserInfo.gender,
							avatar:this.wxUserInfo.avatarUrl
						})
						uni.setStorageSync('uni_id_token', res.result.token)
						uni.setStorageSync('uni_id_token_expired', res.result.tokenExpired)
					}
					if (res.result.type == 'login') {
						console.log("欢迎回来")
					} else if (res.result.type == "register") {
						uni.showModal({
							title: "请完善个人资料",
							success: (res) => {
								if (res.confirm) {
									uni.navigateTo({
										url: "../profile/userDetail"
									})
								}
							}
						})
					}
				}).catch((e) => {
					console.error(e)
					uni.showModal({
						showCancel: false,
						content: '微信登录失败，请稍后再试'
					})
				})
			},
			// 获取用户微信基础信息
			getUserInfo: function() {
				var that = this;
				uni.getUserInfo({
					provider: 'weixin',
					success: function(infoRes) {
						that.wxUserInfo = infoRes.userInfo;
						},
						})
						
			},
			onGetPhoneNumber(e){  
			        if(e.detail.errMsg=="getPhoneNumber:fail user deny"){       //用户决绝授权  
			
			            //拒绝授权后弹出一些提示  
			
			        }else{      //允许授权  
			            console.log(e)  
			            e.detail.encryptedData      //加密的用户信息  
			            e.detail.iv     //加密算法的初始向量  时要用到  
			        }  
			    }
		}
	}
</script>

<style>

</style>
